﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Runtime.InteropServices;      //使用 DllImport    和StructLayout

namespace FileAssociationSample
{
    public partial class Form1 : Form
    {
        #region public enum HChangeNotifyFlags

        [Flags]
        public enum HChangeNotifyFlags
        {

            SHCNF_DWORD = 0x0003,
            SHCNF_IDLIST = 0x0000,

            SHCNF_PATHA = 0x0001,

            SHCNF_PATHW = 0x0005,

            SHCNF_PRINTERA = 0x0002,

            SHCNF_PRINTERW = 0x0006,
            SHCNF_FLUSH = 0x1000,
            SHCNF_FLUSHNOWAIT = 0x2000
        }
        #endregion // enum HChangeNotifyFlags
        #region enum HChangeNotifyEventID
        [Flags]
        enum HChangeNotifyEventID
        {
            SHCNE_ALLEVENTS = 0x7FFFFFFF,

            SHCNE_ASSOCCHANGED = 0x08000000,

            SHCNE_ATTRIBUTES = 0x00000800,

            SHCNE_CREATE = 0x00000002,

            SHCNE_DELETE = 0x00000004,

            SHCNE_DRIVEADD = 0x00000100,

            SHCNE_DRIVEADDGUI = 0x00010000,

            SHCNE_DRIVEREMOVED = 0x00000080,

            SHCNE_EXTENDED_EVENT = 0x04000000,

            SHCNE_FREESPACE = 0x00040000,

            SHCNE_MEDIAINSERTED = 0x00000020,

            SHCNE_MEDIAREMOVED = 0x00000040,

            SHCNE_MKDIR = 0x00000008,

            SHCNE_NETSHARE = 0x00000200,

            SHCNE_NETUNSHARE = 0x00000400,

            SHCNE_RENAMEFOLDER = 0x00020000,

            SHCNE_RENAMEITEM = 0x00000001,

            SHCNE_RMDIR = 0x00000010,

            SHCNE_SERVERDISCONNECT = 0x00004000,

            SHCNE_UPDATEDIR = 0x00001000,

            SHCNE_UPDATEIMAGE = 0x00008000,

        }
        #endregion // enum HChangeNotifyEventID

        [DllImport("shell32.dll")]
        static extern void SHChangeNotify(HChangeNotifyEventID wEventId,
                                           HChangeNotifyFlags uFlags,
                                           IntPtr dwItem1,
                                           IntPtr dwItem2);

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string fileType = textBox1.Text;
            if (!fileType.StartsWith("."))
            {
                fileType = "." + fileType;
                textBox1.Text = fileType;
            }
            //Application.StartupPath 这个只是路径
            // Environment.CommandLine ; 这个包含参数
            string appName = Application.ExecutablePath;

            RegistryKey hk_root = Registry.ClassesRoot; //HKEY_CLASSES_ROOT


            //注册自己程序的the ProgID
            if (null == hk_root.OpenSubKey("widebright.mp3")) //The proper format of a ProgID key name is [Vendor or Application].[Component].[Version], separated by periods and with no spaces, as in Word.Document.6. The Version portion is optional but strongly recommended (see Using Versioned PROGIDs).
            {
                RegistryKey progID = hk_root.CreateSubKey("widebright.mp3");
                if (progID == null)
                {
                    MessageBox.Show("创建widebright.mp3 类型ProgID时失败");
                    hk_root.Close();
                    return;
                }
                //创建（默认）键值，显示给用户看的文件类型描述
                progID.SetValue("", "widebright专用的mp3文件 ", RegistryValueKind.String);

                //文件显示的图标
                RegistryKey defaultIcon = progID.CreateSubKey("DefaultIcon");
                if (defaultIcon == null)
                {
                    MessageBox.Show("创建widebright.mp3 类型的DefaultIcon时失败");
                    progID.Close();
                    hk_root.Close();
                    return;
                }
                //创建（默认）键值，指定文件显示图标
                defaultIcon.SetValue("", appName + ",0", RegistryValueKind.String);
                defaultIcon.Close();

                //指定文件动作
                RegistryKey shell = progID.CreateSubKey("shell");
                if (shell == null)
                {
                    MessageBox.Show("创建widebright.mp3 类型的shell键时失败");
                    progID.Close();
                    hk_root.Close();
                    return;
                }
                //open 动作------------------------
                RegistryKey open = shell.CreateSubKey("open");
                if (open == null)
                {
                    MessageBox.Show("创建widebright.mp3 类型的open键时失败");
                    shell.Close();
                    progID.Close();
                    hk_root.Close();
                    return;
                }

                RegistryKey command = open.CreateSubKey("command");
                if (command == null)
                {
                    MessageBox.Show("创建widebright.mp3 类型的command键时失败");
                    open.Close();
                    shell.Close();
                    progID.Close();
                    hk_root.Close();
                    return;
                }
                command.SetValue("", "\"" + appName + "\" \"%1\"", RegistryValueKind.String);
                command.Close();
                open.Close();
                //play动作---------------------
                RegistryKey play = shell.CreateSubKey("play");
                if (play == null)
                {
                    MessageBox.Show("创建widebright.mp3 类型的play键时失败");
                    shell.Close();
                    progID.Close();
                    hk_root.Close();
                    return;
                }
                play.SetValue("", "在widebright的程序中播放", RegistryValueKind.String);
                command = play.CreateSubKey("command");
                if (command == null)
                {
                    MessageBox.Show("创建widebright.mp3 类型的 play->command键时失败");
                    play.Close();
                    shell.Close();
                    progID.Close();
                    hk_root.Close();
                    return;
                }
                command.SetValue("", "\"" + appName + "\" \"%1\"", RegistryValueKind.String);
                command.Close();
                open.Close();
                progID.Close();

            }

            //修改对应文件类型的默认的关联程序
            //因为在系统里面一把mp3都是已经注册的了，所以这里只是简单修改一下关联

            RegistryKey mp3 = hk_root.OpenSubKey(".mp3", true);
            if (mp3 != null)
            {
                mp3.SetValue("", "widebright.mp3", RegistryValueKind.String); //指定用我们 上面的ProgID打开mp3文件
                mp3.Close();
            }

            hk_root.Close();
            //通知系统，文件关联已经是作用，不然可能要等到系统重启才看到效果
            SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
            MessageBox.Show("mp3文件的关联已经修改成功了！");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] arguments = Environment.GetCommandLineArgs();
            if (arguments.Length > 1)
            {
                if (arguments[1].IndexOf(".mp3") > 0)
                {
                    MessageBox.Show("天上掉下了个mp3：" + arguments[1] + ",哈哈 !");
                }

            }
        }
    }
}

